package com.eclink.asset.sys.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eclink.asset.sys.domain.dao.SysUserFavoritesMenu;
import com.eclink.asset.sys.domain.dao.UserCommonMenu;
import com.eclink.asset.sys.domain.dto.UserFavoritesMenuDTO;
import com.eclink.asset.sys.mapper.SysMenuMapper;
import com.eclink.asset.sys.mapper.SysUserFavoritesMenuMapper;
import com.eclink.asset.sys.mapper.UserCommonMenuMapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.system.domain.SysRoleMenu;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;

import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;

import javax.annotation.Resource;

/**
 * 菜单 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysMenuServiceImpl
{

    @Resource
    private SysMenuMapper menuMapper;

    @Resource
    private UserCommonMenuMapper userCommonMenuMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysRoleMenuMapper roleMenuMapper;

    @Resource
    private SysUserFavoritesMenuMapper userFavoritesMenuMapper;

    public List<SysMenu> list()
    {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        return menuMapper.selectList(queryWrapper);

    }

    /**
     * 获取当前用户的菜单
     * @return
     */
    public List<SysMenu> selectMyMenu()
    {
        Long userId = SecurityUtils.getUserId();
        return menuMapper.selectMenuListByUserId(userId);
    }

    public List<Long> getMyFavoritesMenuIds() {
        QueryWrapper<SysUserFavoritesMenu> qw = new QueryWrapper<>();
        Long userId = SecurityUtils.getUserId();
        qw.eq("user_id", userId);
        List<SysUserFavoritesMenu> list = userFavoritesMenuMapper.selectList(qw);
        return list.stream().map(SysUserFavoritesMenu::getMenuId).collect(Collectors.toList());
    }

    /**
     * 保存常用应用
     */
    public void saveMyFavoritesMenu(List<Long> favoritesMenuIds) {
        QueryWrapper<SysUserFavoritesMenu> qw = new QueryWrapper<>();
        Long userId = SecurityUtils.getUserId();
        qw.eq("user_id", userId);
        userFavoritesMenuMapper.delete(qw);
        for(Long menuId : favoritesMenuIds) {
            SysUserFavoritesMenu userFavoritesMenu = new SysUserFavoritesMenu();
            userFavoritesMenu.setMenuId(menuId);
            userFavoritesMenu.setUserId(userId);
            userFavoritesMenuMapper.insert(userFavoritesMenu);
        }
    }

    /**
     * 获取当前用户的菜单
     * @return
     */
    public List<UserFavoritesMenuDTO> selectMyFavoritesMenuForCheck()
    {
        List<SysMenu> list = this.selectMyMenu();
        List<Long> myFavoritesMenuIds = getMyFavoritesMenuIds();
        List<UserFavoritesMenuDTO> res = new ArrayList<>();
        for (SysMenu menu : list) {
            UserFavoritesMenuDTO dto = new UserFavoritesMenuDTO();
            BeanUtils.copyProperties(menu, dto);
            if (myFavoritesMenuIds.contains(dto.getMenuId())) {
                dto.setChecked(true);
            }
            res.add(dto);
        }
        return res;
    }

    /**
     * 获取当前用户的常用菜单
     * @return
     */
    public List<UserFavoritesMenuDTO> selectMyFavoritesMenu()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> list = menuMapper.selectUserFavoritesMenu(userId);
        List<Long> myFavoritesMenuIds = getMyFavoritesMenuIds();
        List<UserFavoritesMenuDTO> res = new ArrayList<>();
        for (SysMenu menu : list) {
            UserFavoritesMenuDTO dto = new UserFavoritesMenuDTO();
            BeanUtils.copyProperties(menu, dto);
            if (myFavoritesMenuIds.contains(dto.getMenuId())) {
                dto.setChecked(true);
            }
            res.add(dto);
        }
        return res;
    }

    /**
     * 获取默认的常用的常用菜单
     * @return 列表
     */
    List<SysMenu> getDefaultCommonMenuList() {
        QueryWrapper<SysMenu> qw = new QueryWrapper<>();
        qw.eq("common_flag", 1);
        return menuMapper.selectList(qw);
    }

    /**
     * 重置当前用户的常用菜单
     * @return 用户常用菜单
     */
    public List<SysMenu> resetMyFavoritesMenu()
    {
        Long userId = SecurityUtils.getUserId();
        QueryWrapper<SysUserFavoritesMenu> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        userFavoritesMenuMapper.delete(qw);

        List<SysMenu> commonMenuList = getDefaultCommonMenuList();
        for (SysMenu menu : commonMenuList) {
            SysUserFavoritesMenu userFavoritesMenu = new SysUserFavoritesMenu();
            userFavoritesMenu.setMenuId(menu.getMenuId());
            userFavoritesMenu.setUserId(userId);
            userFavoritesMenuMapper.insert(userFavoritesMenu);
        }
        return commonMenuList;
    }

    public List<SysMenu> selectMenuListTop()
    {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getStatus, 0);
        queryWrapper.orderByAsc(SysMenu::getOrderNum);
        return menuMapper.selectList(queryWrapper);
    }

    public List<SysMenu> getCommonMenuList() {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getStatus, 0);
        queryWrapper.eq(SysMenu::getCommonFlag, 1);
        return menuMapper.selectList(queryWrapper);
    }

    /**
     * 保存用户常用菜单
     */
    public void saveCommonMenu(Long userId, List<SysMenu> menuList) {
        for(SysMenu menu : menuList) {
            UserCommonMenu userCommonMenu = new UserCommonMenu();
            userCommonMenu.setMenuId(menu.getMenuId());
            userCommonMenu.setUserId(userId);
            userCommonMenuMapper.insert(userCommonMenu);
        }

    }

    public List<SysMenu> getUserCommonMenu()
    {
        Long userId = SecurityUtils.getUserId();
        MPJLambdaWrapper<SysMenu> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(SysMenu.class).innerJoin(UserCommonMenu.class, UserCommonMenu::getMenuId, SysMenu::getMenuId);
        queryWrapper.eq(SysMenu::getStatus, 0);
        queryWrapper.eq(UserCommonMenu::getUserId, userId);
        List<SysMenu> commonMenuList = menuMapper.selectList(queryWrapper);
        if (commonMenuList == null || commonMenuList.isEmpty()) {
            commonMenuList = this.getCommonMenuList();
            this.saveCommonMenu(userId, commonMenuList);
        }
        return commonMenuList;
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param menus 菜单列表
     * @return 树结构列表
     */

    public List<SysMenu> buildMenuTree(List<SysMenu> menus)
    {
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysMenu dept : menus)
        {
            tempList.add(dept.getMenuId());
        }
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */

    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus)
    {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     * 
     * @param menuId 菜单ID
     * @return 菜单信息
     */

    public SysMenu selectMenuById(Long menuId)
    {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 是否存在菜单子节点
     * 
     * @param menuId 菜单ID
     * @return 结果
     */

    public boolean hasChildByMenuId(Long menuId)
    {
        int result = menuMapper.hasChildByMenuId(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 查询菜单使用数量
     * 
     * @param menuId 菜单ID
     * @return 结果
     */

    public boolean checkMenuExistRole(Long menuId)
    {
        int result = roleMenuMapper.checkMenuExistRole(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 新增保存菜单信息
     * 
     * @param menu 菜单信息
     * @return 结果
     */

    public int insertMenu(SysMenu menu)
    {
        return menuMapper.insert(menu);
    }

    /**
     * 修改保存菜单信息
     * 
     * @param menu 菜单信息
     * @return 结果
     */

    public int updateMenu(SysMenu menu)
    {
        return menuMapper.updateById(menu);
    }

    /**
     * 删除菜单管理信息
     * 
     * @param menuId 菜单ID
     * @return 结果
     */

    public int deleteMenuById(Long menuId)
    {
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_id", menuId);
        roleMenuMapper.delete(queryWrapper);
        return menuMapper.deleteById(menuId);
    }

    /**
     * 获取路由名称
     * 
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
//        if (isMenuFrame(menu))
//        {
//            routerName = StringUtils.EMPTY;
//        }
        return routerName;
    }

    /**
     * 获取路由地址
     * 
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
//        if (menu.getParentId().intValue() != 0 && isInnerLink(menu))
//        {
//            routerPath = StringUtils.replaceEach(routerPath, new String[] { Constants.HTTP, Constants.HTTPS }, new String[] { "", "" });
//        }
        // 非外链并且是一级目录（类型为目录）
//        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
//                && UserConstants.NO_FRAME.equals(menu.getIsFrame()))
//        {
//            routerPath = "/" + menu.getPath();
//        }
//        // 非外链并且是一级目录（类型为菜单）
//        else if (isMenuFrame(menu))
//        {
//            routerPath = "/";
//        }
        return routerPath;
    }

    /**
     * 获取组件信息
     * 
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu)
    {
        String component = UserConstants.LAYOUT;
        return component;
    }

    /**
     * 根据父节点的ID获取所有子节点
     * 
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     * 
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        for (SysMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
